package com.fyl.listener;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class ContextLoaderListener implements ServletContextListener {
//    @Override
//    public void contextInitialized(ServletContextEvent sce) {
//        System.out.println("ContextLoaderListener init ......");
//        //1.创建spring容器
//        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext2.xml");
//        //2.将容器存储到servletContext域中
//        sce.getServletContext().setAttribute("applicationContext", applicationContext);
//    }

//硬编码抽取出去
    private String CONTEXT_CONFIG_LOCATION = "contextConfigLocation";
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("ContextLoaderListener init ......");
        ServletContext servletContext = sce.getServletContext();
        //0.获取配置文件的名称
        String contextConfigLocation = servletContext.getInitParameter(CONTEXT_CONFIG_LOCATION);
        contextConfigLocation = contextConfigLocation.substring("classpath:".length());
        //1.创建spring容器
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext(contextConfigLocation);
        //2.将容器存储到servletContext域中
        servletContext.setAttribute("applicationContext", applicationContext);
    }
}
